package com.profound.notes.component;

import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Objects;

/**
 * @author zjwujlei
 * @date 2021/4/29
 * @email zjwujlei@sina.com
 * @description
 */

public class Recycler {

    public static final int DIRECTION_UP = 0;
    public static final int DIRECTION_DOWN = 2;

    private ArrayList<RecyclerItem> mAllScrap = new ArrayList<>();
    private LinkedList<RecyclerItem> mAttachedScrap = new LinkedList<>();
    private LinkedList<Component> mCacheScrap = new LinkedList<Component>();
    private BaseItemProvider mProvider;
    private SpanLayout mSpanLayout;
    private int direction = 0;

    public Recycler(SpanLayout layout, BaseItemProvider provider) {
        this.mSpanLayout = layout;
        this.mProvider = provider;
    }

    public ArrayList<RecyclerItem> getAllScrap() {
        return mAllScrap;
    }

    public LinkedList<RecyclerItem> getAttachedScrap() {
        return mAttachedScrap;
    }

    public void cacheItem(int index, RecyclerItem item) {
        mAllScrap.add(index, item);
    }

    public void attachComponent(RecyclerItem item) {
        mAttachedScrap.add(item);
    }

    public Component getView(int index, ComponentContainer container) {
        Component cache = mCacheScrap.poll();
        return mProvider.getComponent(index, cache, container);
    }

    public void addItem(int index,RecyclerItem item) {
        mAllScrap.add(index,item);
    }

    public void attachItemToEnd(RecyclerItem item) {
        mAttachedScrap.add(item);
    }

    public void attachItemToStart(RecyclerItem item) {
        mAttachedScrap.add(0,item);
    }

    public void recycle(RecyclerItem item) {
        mSpanLayout.removeComponent(item.child);
        mAttachedScrap.remove(item);
        mCacheScrap.push(item.child);
        item.child = null;
    }

    public void recoverToEnd(RecyclerItem item) {
        Component child = mProvider.getComponent(item.index, mCacheScrap.poll(), mSpanLayout);
        child.estimateSize(
                Component.EstimateSpec.getSizeWithMode(item.width, Component.EstimateSpec.PRECISE),
                Component.EstimateSpec.getSizeWithMode(item.height, Component.EstimateSpec.PRECISE)
        );
        item.child = child;
        mAttachedScrap.add(item);
        mSpanLayout.addComponent(child);
    }

    public void recoverToStart(RecyclerItem item) {
        Component child = mProvider.getComponent(item.index, mCacheScrap.poll(), mSpanLayout);
        child.estimateSize(
                Component.EstimateSpec.getSizeWithMode(item.width, Component.EstimateSpec.PRECISE),
                Component.EstimateSpec.getSizeWithMode(item.height, Component.EstimateSpec.PRECISE)
        );
        item.child = child;
        mAttachedScrap.add(0,item);
        mSpanLayout.addComponent(child);
    }


}
